package com.code;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;

public class QRCode {
	
	public void decode(File file){
		BufferedImage image = null;
		
		try {
			
			image = ImageIO.read(file);
			
			if( image == null ){
				System.out.println("Could not decode image");
			}
			
			LuminanceSource source = new BufferedImageLuminanceSource(image);
			BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
			
			Result result;
			
			@SuppressWarnings("rawtypes")
			Hashtable<DecodeHintType, String> hints = new Hashtable();
			
			// 解码设置编码方式为：utf-8
			hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
			result = new MultiFormatReader().decode(bitmap, hints);
			String resultStr = result.getText();
			System.out.println("解析后内容：" + resultStr);
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		finally{
			image.flush();
		}
	}
	
	public static final void main(String[] arg0){
		System.out.println("==============================");
		File file = new File("d:/2D.jpg");
		
		QRCode qr = new QRCode();
		qr.decode(file);
		
		System.out.println("==============================");
	}

}
